from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base
from sqlalchemy import create_engine, Column, Integer, String, UniqueConstraint, Text, exc, DateTime, inspect, ARRAY, \
    or_, and_, JSON, DATETIME

# 创建基类
Base = declarative_base()
# 定义模型
class Project_Table(Base):
    __tablename__ = 'history'
    history_id = Column(Integer, primary_key=True, autoincrement=True, comment='自增主键')  # 自增主键
    user_id = Column(Integer, nullable=False, comment='用户ID')
    file_name = Column(String(255), nullable=False, comment='docx文件名')
    bubble = Column(JSON, nullable=False, comment='气泡')
    fileId = Column(String(255), nullable=False, comment='加密docx的ID')
    status_code = Column(Integer, nullable=False, comment='状态码，0表示待选状态，1表示采用')
    slice_index = Column(Integer, nullable=False, comment='切片索引')
    update_time = Column(DATETIME, nullable=False, comment='气泡修改时间')

    __table_args__ = (
        UniqueConstraint('user_id', 'fileId', 'slice_index', name='唯一值'),
    )

# 创建数据库引擎和会话
DATABASE_URI = 'mysql+pymysql://root:grow1234@nj-cdb-1mwvwkzt.sql.tencentcdb.com:63972/stock_exchange'
POOL_SIZE = 200
MAX_OVERFLOW = 300
engine = create_engine(DATABASE_URI, pool_size=POOL_SIZE, max_overflow=MAX_OVERFLOW)

# 检查表格是否已存在
inspector = inspect(engine)
if not inspector.has_table("history"):
    # 表格不存在，创建表格
    Base.metadata.create_all(engine)
    print('表格已成功创建')
else:
    # 表格已存在
    print('表格已存在，无需创建')

# 假设engine是预先创建好的数据库引擎
DBSession = scoped_session(sessionmaker(bind=engine))